<script setup lang="ts">
//搜索
import { ref, computed } from "vue";
import axios from "axios";
//传来的值
const dataLocal = (window as any).dataLocal;

//请求地址
const ajaxurl = dataLocal.ajaxurl;

//获取搜索值
const searchQuery = ref("");

//类型
interface ValueData {
  id: number;
  zi: string;
  py: string;
  pinyin: string;
  wubi: string;
  bushou: string;
  bihua: number;
  jijie: string;
  xiangjie: string;
}

interface Value {
  code: string;
  message: string;
  data: ValueData;
}

//返回值
const value = ref({} as Value);

//新华字典接口
const getXh = async () => {
  try {
    const response = await axios.post(
      ajaxurl,
      {
        action: "get_xh_callback",
        word: searchQuery.value,
      },
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded", // 设置 Content-Type axios会自动将JavaScript对象序列化为表单数据形式
        },
      }
    );
    value.value = response.data.data;
  } catch (error) {
    console.error(error);
  }
};
//计算有没有拿到值
const hasValue = computed(() => {
  return Object.keys(value.value).length > 0;
});
</script>
<template>
  <hr />
  查字：<input type="text" v-model="searchQuery" />

  <hr />
  <button class="button button-primary" @click="getXh">查询</button>
  <div v-if="hasValue">
    <h3>返回的数据</h3>
    {{ value }}
    <hr />
    <ul>
      <li>代码：{{ value.code }}</li>
      <li>信息 ：{{ value.message }}</li>
      <li>ID ：{{ value.data.id }}</li>

      <li>查询的字 ：{{ value.data.zi }}</li>
      <li>拼音 ：{{ value.data.py }}</li>
      <li>读音：{{ value.data.pinyin }}</li>
      <li>五笔：{{ value.data.wubi }}</li>
      <li>部首：{{ value.data.bushou }}</li>
      <li>笔画数：{{ value.data.bihua }}</li>
      <li>
        简解：

        <dd v-for="(item, index) in value.data.jijie" :key="index">
          {{ item }}
        </dd>
      </li>
      <li>
        详解：
        <dd v-for="(item, index) in value.data.xiangjie" :key="index">
          {{ item }}
        </dd>
      </li>
    </ul>
  </div>
</template>

<style scoped></style>
